<script lang="ts" setup>
import { Model } from "./model";
import { superAdmin, handleTable_initData } from "./initData";

import type { TreeInstance, CheckboxValueType } from "element-plus";

const PageConfig = {
  //被操作实体的名称
  entity: "role",
  entityName: "角色",
  hideDetailBtn: true,
};
const dialogVisible_edit_permission = ref(false);
const activeTab = ref("menu");
const callbackMessage = ref({
  show: false,
  valid: true,
  content: "",
});
let handle_row: any = {};
const menuStore = useMenuStore();
const ref_menuTree = ref<TreeInstance>();
const ref_table = ref(null);
const handle_tableData = reactive(handleTable_initData);

// 按钮 -- 配置权限
const edit_permission = async (row: any) => {
  activeTab.value = "menu";
  handle_row = JSON.parse(JSON.stringify(row));
  dialogVisible_edit_permission.value = true;
  await nextTick();
  let permissionDic = handle_row.permissionDic;
  let menu_permission = permissionDic.menu || [];
  ref_menuTree.value!.setCheckedKeys(menu_permission);
  let handle_permission = permissionDic.handle || [];
  handle_tableData.forEach((item: any) => {
    item.permissionList = [];
    item.checkAll = false;
    item.isIndeterminate = false;
    let baseList = [];
    if (!item.hideAdd) {
      baseList.push(`${item.entity}:add`);
    }
    if (!item.hideEdit) {
      baseList.push(`${item.entity}:edit`);
    }
    if (!item.hideDel) {
      baseList.push(`${item.entity}:del`);
    }
    if (!item.hideDetail) {
      baseList.push(`${item.entity}:detail`);
    }
    baseList.forEach((item_temp: any) => {
      let index = handle_permission.indexOf(item_temp);
      if (index > -1) {
        item.permissionList.push(item_temp);
        handle_permission.splice(index, 1);
      }
    });
    if (Array.isArray(item.extra_handleList)) {
      item.extra_handleList.forEach((item_temp: any) => {
        let target = `${item.entity}:${item_temp.code}`;
        let index = handle_permission.indexOf(target);
        if (index > -1) {
          item.permissionList.push(target);
          handle_permission.splice(index, 1);
        }
      });
    }
    getAll_handlePermissionList(item);
    if (isEqualArray_simple(item.AllPermissionList, item.permissionList)) {
      item.checkAll = true;
    }
    if (
      item.permissionList.length > 0 &&
      item.permissionList.length < item.AllPermissionList.length
    ) {
      item.isIndeterminate = true;
    }
  });
};

// 按钮 -- 保存配置的权限
const save_permission = async () => {
  let handle_permissionList: any = [];
  handle_tableData.forEach((item: any) => {
    handle_permissionList.push(...item.permissionList);
  });
  let permissionDic = {
    menu: ref_menuTree
      .value!.getCheckedNodes(false, true)
      .map((menuNode) => menuNode.path),
    handle: handle_permissionList,
  };
  // 使用拦截器自动添加认证头
  try {
    await $fetch(`/api/role/edit`, {
      body: {
        ...handle_row,
        permissionDic: permissionDic,
      },
      method: "POST",
    });
    callbackMessage.value = {
      show: true,
      valid: true,
      content: "操作成功",
    };
    setTimeout(() => {
      dialogVisible_edit_permission.value = false;
      ref_table.value && (ref_table.value as any).saveOK();
    }, 500);
  } catch (error) {
    console.log(error);
  }
};

// 获取所有的操作权限
const getAll_handlePermissionList = (row: any) => {
  if (
    Array.isArray(row.AllPermissionList) &&
    row.AllPermissionList.length > 0
  ) {
    return row.AllPermissionList;
  }
  let AllPermissionList = [];
  if (!row.hideAdd) {
    AllPermissionList.push(`${row.entity}:add`);
  }
  if (!row.hideEdit) {
    AllPermissionList.push(`${row.entity}:edit`);
  }
  if (!row.hideDel) {
    AllPermissionList.push(`${row.entity}:del`);
  }
  if (!row.hideDetail) {
    AllPermissionList.push(`${row.entity}:detail`);
  }
  if (row.extra_handleList) {
    AllPermissionList.push(
      ...row.extra_handleList.map((item: any) => `${row.entity}:${item.code}`)
    );
  }
  row.AllPermissionList = AllPermissionList;
  return AllPermissionList;
};

// 配置权限弹窗中 -- 操作权限 -- 勾选权限子项的回调
const handleCheckAllChange = (val: CheckboxValueType, row: any) => {
  const { permissionList } = toRefs(row);
  permissionList.value = val
    ? row.AllPermissionList || getAll_handlePermissionList(row)
    : [];
  row.isIndeterminate = false;
};

// 配置权限弹窗中 -- 操作权限 -- 勾选操作对象的回调
const handleCheckedChange = (value: CheckboxValueType[], row: any) => {
  let AllPermissionList_length = (
    row.AllPermissionList || getAll_handlePermissionList(row)
  ).length;
  const checkedCount = value.length;
  row.checkAll = checkedCount === AllPermissionList_length;
  row.isIndeterminate =
    checkedCount > 0 && checkedCount < AllPermissionList_length;
};

// 列表加载完成的回调
const getList_done = async (data: any[], total: number) => {
  if (total === 0) {
    // 自动创建超级管理员
    let new_addsuerAdmin = debounce(addsuerAdmin);
    new_addsuerAdmin();
    setTimeout(() => {
      ref_table.value && (ref_table.value as any).getList();
    }, 1000);
  }
};

// 访问接口--新增超级管理员
const addsuerAdmin = async () => {
  await $fetch(`/api/role/add`, {
    body: superAdmin,
    method: "POST",
  });
};
</script>
<template>
  <S-comMangeInfo
    ref="ref_table"
    :Model="Model"
    :PageConfig="PageConfig"
    @getList_done="getList_done"
  >
    <template #myHandle="{ row }">
      <el-button
        v-if="row.name !== '超级管理员'"
        link
        type="primary"
        size="small"
        @click="edit_permission(row)"
        >配置权限</el-button
      >
    </template>
  </S-comMangeInfo>
  <el-dialog
    v-model="dialogVisible_edit_permission"
    title="配置权限"
    width="600"
  >
    <el-tabs type="border-card" v-model="activeTab">
      <el-tab-pane label="菜单权限" name="menu">
        <el-tree
          ref="ref_menuTree"
          show-checkbox
          :data="menuStore.menu_list"
          node-key="path"
          default-expand-all
          :expand-on-click-node="false"
          :indent="40"
        >
        </el-tree>
      </el-tab-pane>
      <el-tab-pane label="操作权限" name="handle">
        <el-table :data="handle_tableData" border>
          <el-table-column
            label="操作对象"
            prop="entityName"
            align="center"
            width="100"
          >
            <template #default="scope">
              <el-checkbox
                v-model="scope.row.checkAll"
                :indeterminate="scope.row.isIndeterminate"
                @change="handleCheckAllChange($event, scope.row)"
              >
                {{ scope.row.entityName }}
              </el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="操作方式" align="center">
            <template #default="scope">
              <el-checkbox-group
                v-model="scope.row.permissionList"
                @change="handleCheckedChange($event, scope.row)"
                class="flex flex-wrap"
              >
                <el-checkbox
                  v-if="!scope.row.hideAdd"
                  :label="scope.row.add_nickName || '新增'"
                  :value="`${scope.row.entity}:add`"
                />
                <el-checkbox
                  v-if="!scope.row.hideEdit"
                  :label="scope.row.edit_nickName || '编辑'"
                  :value="`${scope.row.entity}:edit`"
                />
                <el-checkbox
                  v-if="!scope.row.hideDel"
                  :label="scope.row.del_nickName || '删除'"
                  :value="`${scope.row.entity}:del`"
                />
                <el-checkbox
                  v-if="!scope.row.hideDetail"
                  label="详情"
                  :value="`${scope.row.entity}:detail`"
                />
                <el-checkbox
                  v-for="item in scope.row.extra_handleList"
                  :label="item.name"
                  :value="`${scope.row.entity}:${item.code}`"
                />
              </el-checkbox-group>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible_edit_permission = false"
          >取消</el-button
        >
        <el-button type="primary" @click="save_permission"> 保存 </el-button>
      </div>
    </template>
    <S-msgWin :msg="callbackMessage" :duration="1000" />
  </el-dialog>
</template>
